package com.instalinks.android.apps.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.instalinks.android.apps.helper.AppConfig;
import com.instalinks.android.lib.AppHelper;
import com.instalinks.android.lib.ApplicationNotifications;
import com.instalinks.android.lib.LibConstants;
import com.instalinks.android.lib.enums.ExternalActivityType;

public class C2dmReceiver extends BroadcastReceiver {

	private AppConfig mAppCfg;
	private ApplicationNotifications appNotifications;
	private Context mContext;

	@Override
	public void onReceive(Context context, Intent intent) {
		mAppCfg = new AppConfig(context);
		mContext = context;

		if (intent.getAction().equals(
				LibConstants.IntentAction.C2DM_REGISTRATION)) {
			handleRegistration(context, intent);
		} else if (intent.getAction().equals(
				LibConstants.IntentAction.C2DM_RECEIVE)) {
			handleMessage(context, intent);
		}
	}

	private void handleRegistration(Context context, Intent intent) {
		String registration = intent.getStringExtra("registration_id");

		appNotifications = mAppCfg.getExternalNotificationInstance(true);

		if (intent.getStringExtra("error") != null) {
			// Registration failed, should try again later.
			Log.d("c2dm", "registration failed");
			String error = intent.getStringExtra("error");
			if (error == "SERVICE_NOT_AVAILABLE") {
				Log.d("c2dm", "SERVICE_NOT_AVAILABLE");
			} else if (error == "ACCOUNT_MISSING") {
				Log.d("c2dm", "ACCOUNT_MISSING");
			} else if (error == "AUTHENTICATION_FAILED") {
				Log.d("c2dm", "AUTHENTICATION_FAILED");
			} else if (error == "TOO_MANY_REGISTRATIONS") {
				Log.d("c2dm", "TOO_MANY_REGISTRATIONS");
			} else if (error == "INVALID_SENDER") {
				Log.d("c2dm", "INVALID_SENDER");
			} else if (error == "PHONE_REGISTRATION_ERROR") {
				Log.d("c2dm", "PHONE_REGISTRATION_ERROR");
			}
			appNotifications.notify("Reg/UnReg for Notifications Failed : "
					+ error);
		} else if (intent.getStringExtra("unregistered") != null) {
			Log.d("c2dm", "unregistered");
			appNotifications.notify("Device UnRegistered for Notifications");
			mAppCfg.sendRegistrationIdToHost("UNREG");

			try {
				mAppCfg.setRegistrationId("UNREG");
			} catch (Exception e) {
				AppHelper.alert(
						mContext,
						"Unable to save EMPTY Registration Id : "
								+ e.getMessage());
			}

		} else if (registration != null) {
			Log.d("c2dm", registration);

			appNotifications.notify("Device Registered for Notifications");
			boolean result = mAppCfg.sendRegistrationIdToHost(registration);

			if (result) {
				try {
					mAppCfg.setRegistrationId(registration);
				} catch (Exception e) {
					AppHelper.alert(
							mContext,
							"Unable to save Registration Id : "
									+ e.getMessage());
				}
			}
		}
	}

	private void handleMessage(Context context, Intent intent) {

		String mode = intent.getExtras().getString(LibConstants.BroadcastFields.mode).toLowerCase();
		String appId = intent.getExtras().getString(LibConstants.BroadcastFields.appid);
		String field1 = intent.getExtras().getString(LibConstants.BroadcastFields.field1);
		String field2 = intent.getExtras().getString(LibConstants.BroadcastFields.field2);
		String field3 = intent.getExtras().getString(LibConstants.BroadcastFields.field3);
		String field4 = intent.getExtras().getString(LibConstants.BroadcastFields.field4);

		if (appId == null)
			appId = "";

		if (field2 == null)
			field2 = "";

		if (field3 == null)
			field3 = "";

		if (field4 == null)
			field4 = "";

		appId = appId.toLowerCase();
		field3 = field3.toLowerCase();

		// AppNotificationProcessor processor = new AppNotificationProcessor();

		if (mode.equalsIgnoreCase("flash")) { // GENERIC FLASH
			processFlash(field1, field2);
		} else if (mode.equalsIgnoreCase("system")
				&& field3.equalsIgnoreCase("sms")) { // SYSTEM SMS
			processSystemSms(field1, field2);
		} else {

//			appId = "com.instalinks.android.apps.smspostservice";

			Intent i = new Intent();
			i.setAction(com.instalinks.android.lib.LibConstants.IntentAction.NOTIFICATION_BROADCAST);

			Bundle bundle = new Bundle();
			bundle.putString(LibConstants.BroadcastFields.mode, mode);
			bundle.putString(LibConstants.BroadcastFields.appid, appId);
			bundle.putString(LibConstants.BroadcastFields.field1, field1);
			bundle.putString(LibConstants.BroadcastFields.field2, field2);
			bundle.putString(LibConstants.BroadcastFields.field3, field3);
			bundle.putString(LibConstants.BroadcastFields.field4, field4);
			i.putExtras(bundle);

			this.mContext.sendBroadcast(i);

		}
	}

	private void processFlash(String message, String sender) {
		AppHelper.addMessagesToInbox(mContext,
				(sender.trim().length() == 0) ? "TS-SUPPORT" : sender, message);
		
		appNotifications = mAppCfg.getExternalNotificationInstance(true);
		appNotifications.notify("Click to open messages",
				ExternalActivityType.MessageBox.toString());
	}

	private void processSystemSms(String message, String phoneNumbers) {
		AppHelper.sendMultipleSms(mContext, phoneNumbers, message, false);
	}
}
